<template>
	<view class="all-main">
		<view class="main">
			<u-sticky>
				<view class="subsectionType">
					<u-subsection :list="list" mode="subsection" :current="curNow" @change="sectionChange"></u-subsection>
				</view>
			</u-sticky>
			<view v-if="curNow == 0" class="scans">
				<view class="selecteds">
					<u-tabs :list="list1" :scrollable="false" @change="tabsChange"></u-tabs>
				</view>
				<view v-if="scanNow==0" class="one_scan">
					<view class="lefts">
						<u--input placeholder="扫码或输入SN" border="surround" v-model="sn"></u--input>
					</view>
					<view class="rights">
						<!-- #ifdef APP -->
						<u-icon name="scan" size="32" @click="one_scan"></u-icon>
						<!-- #endif -->
						<!-- #ifdef H5 -->
						<u-icon name="scan" size="32" @click="one_scan_wx"></u-icon>
						<!-- #endif -->
					</view>
				</view>
				<view v-else class="batch_scan">
					<view class="top">
						<view class="lefts">
							<!-- <u--input placeholder="[序列开始] 扫码或输入SN" border="surround" v-model="startSn"></u--input> -->
							<cus-selects v-model="startSn" placeholder="[序列开始] 扫码或输入SN" :data="mySnListSearch" :clearable='true' :filterable='true' :searchType='1' :size="300"></cus-selects>
						</view>
						<view class="rights">
							<!-- #ifdef APP -->
							<u-icon name="scan" size="32" @click="start_scan"></u-icon>
							<!-- #endif -->
							<!-- #ifdef H5 -->
							<u-icon name="scan" size="32" @click="start_scan_wx"></u-icon>
							<!-- #endif -->
						</view>
					</view>
					<view class="bottom">
						<view class="lefts">
							<!-- <u--input placeholder="[序列结束] 扫码或输入SN" border="surround" v-model="endSn"></u--input> -->
							<cus-selects v-model="endSn" placeholder="[序列结束] 扫码或输入SN" :data="mySnListSearch" :clearable='true' :filterable='true' :searchType='1' :size="300"></cus-selects>
						</view>
						<view class="rights">
							<!-- #ifdef APP -->
							<u-icon name="scan" size="32" @click="end_scan"></u-icon>
							<!-- #endif -->
							<!-- #ifdef H5 -->
							<u-icon name="scan" size="32" @click="end_scan_wx"></u-icon>
							<!-- #endif -->
						</view>
					</view>
				</view>
			</view>
			<view v-else-if="curNow == 1" class="listSelection">
				<view class="titles">
					<view class="lefts">
						列表选择
					</view>
					<view class="rights">
						<!-- <u-search :showAction="true" actionText="搜索" :animation="true" inputAlign="right" height="16"></u-search> -->
						<view class="" @click="allSelect">
							全选
						</view>
					</view>
				</view>
				<u-line></u-line>
				<view class="snList">
					<u-checkbox-group v-model="checkSnData" placement="column">
						<view v-for="(item, index) in mySnList" :key="index" class="snItem">
							<view class="lefts">
								{{item}}
							</view>
							<view class="rights">
								<u-checkbox :name="item" activeColor="#2979ff"></u-checkbox>
							</view>
						</view>
					</u-checkbox-group>
				</view>
			</view>
			<view class="bottomBtn">
				<view class="btns" @click="snAdd">
					添 加
				</view>
			</view>
			<view class="dataList">
				<view class="titles">
					<view class="lefts">
						已选终端SN
					</view>
					<view class="rights">
						<text v-if="isEdit == 1" class="editBtn" @click="editFun">编辑</text>
						<view v-else class="cancel">
							<view class="cancelBtn" @click="editFun">
								取消
							</view>
							<view class="cancelBtn" @click="allSelectSn">
								全部
							</view>
							<view class="" @click="snDel">
								<u-icon name="trash" color="#fa3534" size="18" bold></u-icon>
							</view>
						</view>
					</view>
				</view>
				<u-line></u-line>
				<view v-if="selectSnData.length > 0" class="lists">
					<u-checkbox-group v-model="checkData" placement="column">
						<view v-for="(item, index) in selectSnData" :key="index" class="items">
							<view class="lefts">
								{{item}}
							</view>
							<view v-if="isEdit == 2" class="rights">
								<u-checkbox :name="item" activeColor="red"></u-checkbox>
							</view>
						</view>
					</u-checkbox-group>
				</view>
				<u-empty v-else text="您还没有选择终端" icon="/static/Empty/search_null.png"></u-empty>
			</view>
			<view class="shipments" :class="[selectSnData.length == nums?'yellow':'']" @click="shipments">
				发  货 ({{selectSnData.length}} / {{nums}})
			</view>
		</view>
	</view>
</template>

<script>
	import cusSelects from '@/components/cus-selects-fan/cus-selects-fan.vue'
	var util = require('@/util/request5.js');
	/*#ifdef H5*/
	import wx from 'weixin-js-sdk';
	/*#endif*/
	export default {
		components: {
			cusSelects
		},
		data() {
			return {
				list: ['扫码', '列表选择'],
				list1: [{
					name: '单扫'
				}, {
					name: '批量'
				}],
				curNow: 0,
				scanNow: 0,
				sn: '',
				startSn: '',
				endSn: '',
				mySnList: [],
				mySnListSearch: [],
				selectSnData: [],
				checkData: [],
				checkSnData: [],
				isEdit: 1,
				id: 0,
				product_id: 0,
				nums: 0,
				userinfo: {}
			}
		},
		onLoad(e) {
			this.userinfo = uni.getStorageSync('userinfo');
			this.id = e.id
			this.product_id = e.pid
			this.nums = e.nums
			/*#ifdef H5*/
			this.injectConfig()
			/*#endif*/
			this.getFreeEquip()
		},
		methods: {
			// 获取我的终端
			async getFreeEquip() {
				const {
					data: res
				} = await this.$myHttp5({
					url: 'setting/getFreeEquip',
					data: {
						product_id: this.product_id
					},
					header: {
						'token': this.userinfo.token
					}
				});
				if (res.code == 1) {
					this.mySnList = res.data
					this.mySnListSearch = []
					for (var i in res.data) {
						this.mySnListSearch.push({
							label: res.data[i],
							value: res.data[i]
						})
					}
				}
			},
			// 类型切换
			sectionChange(index) {
				this.curNow = index
				if (index == 0) {
					this.scanNow = 0
				}
			},
			// 扫码类型切换
			tabsChange(e) {
				this.scanNow = e.index
			},
			// 获取微信配置
			injectConfig() {
				let url = ''
				url = window.location.href;
				uni.request({
					url: util.API_URL + '/api/v1/test',
					// url: util.API_URL + '/api/Wechats/getWechatScan',
					data: {
						url: url
					},
					success: (res) => {
						const data = res.data
						if (data.code == 1) {
							wx.config({
								debug: false, // 开启调试模式,
								appId: data.data.appId, // 必填，企业号的唯一标识
								timestamp: data.data.timestamp, // 必填，生成签名的时间戳
								nonceStr: data.data.nonceStr, // 必填，生成签名的随机串
								signature: data.data.signature, // 必填，签名
								jsApiList: data.data.jsApiList, // 必填，需要使用的JS接口列表
							});
							wx.ready(() => {})
							wx.error(function(err) {});
						}
					},
					fail(err) {}
				});
			},
			// 扫码
			one_scan() {
				let _this = this
				uni.scanCode({
					onlyFromCamera: true,
					scanType: ['barCode'],
					success: function(res) {
						_this.sn = res.result
					}
				});
			},
			one_scan_wx() {
				let _this = this
				wx.scanQRCode({
					needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
					scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
					success: function(res) {
						var resultrow = String(res.resultStr).split(",");
						if (resultrow[0] == 'CODE_128') {
							_this.sn = resultrow[1]
						} else {
							uni.showToast({
								title: '请识别有效的条形码!',
								duration: 2000,
								icon: 'none'
							});
						}
					},
					fail: function(res) {}
				});
			},
			start_scan() {
				let _this = this
				uni.scanCode({
					onlyFromCamera: true,
					scanType: ['barCode'],
					success: function(res) {
						_this.startSn = res.result
					}
				});
			},
			start_scan_wx() {
				let _this = this
				wx.scanQRCode({
					needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
					scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
					success: function(res) {
						var resultrow = String(res.resultStr).split(",");
						if (resultrow[0] == 'CODE_128') {
							_this.startSn = resultrow[1]
						} else {
							uni.showToast({
								title: '请识别有效的条形码!',
								duration: 2000,
								icon: 'none'
							});
						}
					},
					fail: function(res) {}
				});
			},
			end_scan() {
				let _this = this
				uni.scanCode({
					onlyFromCamera: true,
					scanType: ['barCode'],
					success: function(res) {
						_this.endSn = res.result
					}
				});
			},
			end_scan_wx() {
				let _this = this
				wx.scanQRCode({
					needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
					scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
					success: function(res) {
						var resultrow = String(res.resultStr).split(",");
						if (resultrow[0] == 'CODE_128') {
							_this.endSn = resultrow[1]
						} else {
							uni.showToast({
								title: '请识别有效的条形码!',
								duration: 2000,
								icon: 'none'
							});
						}
					},
					fail: function(res) {}
				});
			},
			// 已选终端 - 删除
			snDel() {
				var that = this
				var newDataList = []
				if (this.checkData.length <= 0) {
					uni.showToast({
						title: '请选择要删除的SN',
						icon: 'none'
					})
					return false
				}
				uni.showModal({
					title: '提示',
					content: '确定要删除选择的SN吗？',
					success: function(res) {
						if (res.confirm) {
							for (var i in that.selectSnData) {
								if (that.checkData.indexOf(that.selectSnData[i]) == -1) {
									newDataList.push(that.selectSnData[i])
								}
							}
							that.checkData = []
							that.selectSnData = newDataList
							if (that.selectSnData.length <= 0) {
								that.isEdit = 1
							}
						}
					}
				});
			},
			// 已选终端编辑
			editFun() {
				if (this.isEdit == 1) {
					this.isEdit = 2
				} else {
					this.isEdit = 1
				}
			},
			// 确定加入
			snAdd() {
				// 扫码
				if (this.curNow == 0) {
					// 单扫
					if (this.scanNow == 0) {
						if (this.sn == '') {
							uni.showToast({
								title: '请扫码或输入SN',
								icon: 'none'
							})
							return false
						}
						if (this.selectSnData.indexOf(this.sn) >= 0) {
							uni.showToast({
								title: '该SN已存在',
								icon: 'none'
							})
							return false
						}
						if (this.selectSnData.length >= this.nums) {
							uni.showToast({
								title: '已超出发货数量',
								icon: 'none'
							})
							return false
						}
						this.selectSnData.push(this.sn)
						this.sn = ''
					}
					// 批量
					if (this.scanNow == 1) {
						if (this.startSn == '') {
							uni.showToast({
								title: '请扫码或输入开始SN',
								icon: 'none'
							})
							return false
						}
						if (this.endSn == '') {
							uni.showToast({
								title: '请扫码或输入结束SN',
								icon: 'none'
							})
							return false
						}
						if (this.startSn.length != this.endSn.length) {
							uni.showToast({
								title: '开始SN和结束SN长度不一样',
								icon: 'none'
							})
							return false
						}
						if (this.startSn == this.endSn) {
							if (this.selectSnData.indexOf(this.startSn) == -1) {
								if (this.selectSnData.length >= this.nums) {
									uni.showToast({
										title: '已超出发货数量',
										icon: 'none'
									})
									return false
								}
								this.selectSnData.push(this.startSn)
							}
						} else {
							var startArr = this.startSn.split("")
							var endArr = this.endSn.split("")
							var snStr = ''
							var indexs = 0
							for (var i in startArr) {
								if (startArr[i] == endArr[i]) {
									snStr += '' + startArr[i]
								} else {
									indexs = i
									break
								}
							}
							var strLength = this.startSn.length-indexs
							var staN = this.startSn.substr(indexs, strLength)
							var endN = this.endSn.substr(indexs, strLength)
							if (parseInt(endN) < parseInt(staN)) {
								uni.showToast({
									title: '开始SN和结束SN错误',
									icon: 'none'
								})
								return false
							}
							for (var i = parseInt(staN); i <= parseInt(endN); i++) {
								if (this.selectSnData.indexOf(snStr + String(i).padStart(strLength, '0')) == -1) {
									if (this.selectSnData.length >= this.nums) {
										uni.showToast({
											title: '已超出发货数量',
											icon: 'none'
										})
										return false
									}
									this.selectSnData.push(snStr + String(i).padStart(strLength, '0'))
								}
							}
						}
						this.startSn = ''
						this.endSn = ''
					}
				}
				// 列表
				if (this.curNow == 1) {
					if (this.checkSnData.length <= 0) {
						uni.showToast({
							title: '请选择SN',
							icon: 'none'
						})
						return false
					}
					for (var i in this.checkSnData) {
						if (this.selectSnData.indexOf(this.checkSnData[i]) == -1) {
							if (this.selectSnData.length >= this.nums) {
								uni.showToast({
									title: '已超出发货数量',
									icon: 'none'
								})
								return false
							}
							this.selectSnData.push(this.checkSnData[i])
						}
					}
					this.checkSnData = []
				}
			},
			// 发货
			shipments() {
				var that = this
				if (this.selectSnData.length > 0) {
					if (this.selectSnData.length == this.nums) {
						if (this.selectSnData.length > this.nums) {
							uni.showToast({
								title: '已超出发货数量',
								icon: 'none'
							})
							return false
						}
						uni.showModal({
							title: '提示',
							content: '确定要发货吗？',
							success: function(res) {
								if (res.confirm) {
									that.shipmentsFun()
								}
							}
						});
					}
				}
			},
			// 发货 - 操作
			async shipmentsFun() {
				uni.showLoading({
					title: '加载中'
				});
				const {
					data: res
				} = await this.$myHttp5({
					url: 'setting/saveAllocation',
					data: {
						order_id: this.id,
						product_id: this.product_id,
						sn: this.selectSnData
					},
					header: {
						'token': this.userinfo.token
					}
				});
				uni.hideLoading()
				uni.showToast({
					title: res.msg,
					icon: "none"
				})
				if (res.code == 1) {
					setTimeout(function() {
						uni.navigateBack()
					}, 1500);
				}
			},
			// 全选
			allSelect() {
				if (this.checkSnData.length != this.mySnList.length) {
					this.checkSnData = this.mySnList
				} else {
					this.checkSnData = []
				}
			},
			// 已选 - 全选
			allSelectSn() {
				if (this.checkData.length != this.selectSnData.length) {
					this.checkData = this.selectSnData
				} else {
					this.checkData = []
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	page {
		background-color: #f3f4f6;
	}

	.main {
		padding: 20rpx;
		
		.subsectionType {
			background-color: #ffffff;
		}

		.scans {
			margin-top: 20rpx;
			background-color: #ffffff;

			.selecteds {}

			.one_scan {
				padding: 20rpx;
				display: flex;
				align-items: center;
				justify-content: space-between;

				.lefts {
					width: 90%;
				}
			}

			.batch_scan {
				padding: 20rpx;

				.top {
					display: flex;
					align-items: center;
					justify-content: space-between;
				}

				.bottom {
					margin-top: 20rpx;
					display: flex;
					align-items: center;
					justify-content: space-between;
				}

				.lefts {
					width: 90%;
				}
			}
		}
		
		.listSelection {
			margin-top: 20rpx;
			background-color: #ffffff;
			padding: 20rpx;
			.titles {
				padding-bottom: 20rpx;
				font-size: 28rpx;
				font-weight: bold;
				display: flex;
				justify-content: space-between;
			}
			.snList {
				padding: 10rpx 0;
				font-size: 24rpx;
				height: 400rpx;
				max-height: 400rpx;
				overflow: auto;
				.snItem {
					display: flex;
					justify-content: space-between;
					padding: 10rpx 0;
				}
			}
		}
		
		.bottomBtn {
			padding: 20rpx 0;
		
			.btns {
				background-color: #2979ff;
				color: #ffffff;
				text-align: center;
				border-radius: 12rpx;
				font-weight: bold;
				font-size: 26rpx;
				padding: 10rpx;
			}
		}

		.dataList {
			margin-top: 20rpx;
			background-color: #ffffff;
			padding: 20rpx;
			margin-bottom: 80rpx;

			.titles {
				padding-bottom: 20rpx;
				font-size: 28rpx;
				display: flex;
				justify-content: space-between;
				.lefts {
					font-weight: bold;
				}
				.rights {
					.editBtn {
						padding: 8rpx 30rpx;
						font-size: 24rpx;
						border: 1px solid #909399;
						border-radius: 12rpx;
						color: #909399;
					}
					.cancel {
						display: flex;
						padding-right: 10rpx;
						.cancelBtn {
							margin-right: 20rpx;
						}
					}
				}
			}

			.lists {
				font-size: 24rpx;
				padding: 10rpx 0;

				.items {
					padding: 6rpx 0;
					line-height: 36rpx;
					display: flex;
					justify-content: space-between;
					.lefts {
						
					}
				}
			}
		}
		
		.shipments {
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			padding: 20rpx;
			background-color: #c8c9cc;
			color: #ffffff;
			font-size: 32rpx;
			font-weight: bold;
			text-align: center;
		}
		
		.yellow {
			background-color: #f29100;
		}
	}
</style>